<?php
/**
 * CodeIgniter Image Class
 *
 * 图片存储程序
 *
 * @package		CodeIgniter
 * @author		$Author: wangxiaodong $
 * @subpackage	Libraries
 * @category	Libraries
 * @version     $Id: CT_Image.php 33170 2015-11-18 03:19:18Z wangxiaodong $
 *
 */
class CT_Image 
{
	var $root_path = '';
	
	var $img_host = '';
	
	//文件类型
	var $ext = array(
		'j' => 'jpg',
		'e' => 'jpeg',
		'p' => 'png',
		'g' => 'gif',
	    't' => 'txt',
	    'd' => 'doc',
	    'x' => 'docx',
		'c' => 'csv'
	);
	
	
	
	public function __construct()
	{
		$ci = & get_instance();
		$ci->config->load('image', TRUE);
		$config_image = $ci->config->item('image');
		$module = array_keys($config_image);
		unset($module['path']);
		unset($module['host']);
		foreach ($module as $k) {
		    $this->module[substr($k, 0, 1)] = $k;
		}
		$this->root_path = $config_image['path'];
		$this->img_host = $config_image['host'];
		
	}
	
	public function _resize($path, $new_image = null, $w = 0, $h = 0)
	{
		$ci = & get_instance();
		$config['image_library'] = 'gd2';
		$config['source_image'] = $path;
		$config['create_thumb'] = false;
		$config['maintain_ratio'] = false;
		$config['new_image'] = $new_image;
		$w && $config['width'] = $w;
		$h && $config['height'] = $h;

		$ci->load->library('image_lib', $config);
		$ci->image_lib->initialize($config);
		if(file_exists(dirname($new_image)) == false) {
			mkdir(dirname($new_image), 0775, true);
		}
		$ci->image_lib->resize();
		$ci->image_lib->clear();
	}
	
	
	//图片裁切
	public function resize($pid, $w = 0, $h = 0)
	{
		$ci = & get_instance();
		$ci->load->library('CT_Mcrypt');
		$size = $this->makesize($w, $h);
		$source = $ci->ct_mcrypt->decode($pid);
		$fileinfo  = explode("_", $source);
		$module_arr = $this->module;
		$module_name = $module_arr[$fileinfo[0]];
		$name = $this->pid2path($pid);
		$save = $this->root_path . $module_name ."/" .  "origin" . "/"  . $name;
		$new = str_replace("origin", $size, $save);
		return $this->_resize($save, $new, $w, $h);
			
	}
	
	//创建图片尺寸目录
	//w表示定宽，h表示定高
	public function makesize($w = 0, $h = 0)
	{
		$w && $h && $size = 'wh' . $w . "x" . $h;
		empty($size) && $w && $size = 'w' . $w;
		empty($size) && $h && $size .= 'h' . $h;
		empty($size) && $size = "origin";
		return $size;
	}
	
	//pid格式 image_id_ext（扩展名）
	public function pid2path($pid)
	{
		$ci = & get_instance();
		$ci->load->library('CT_Mcrypt');
		$source = $ci->ct_mcrypt->decode($pid);
		$fileinfo  = explode("_", $source);
		$exten = $fileinfo[2];
		$ext = $this->ext[$exten];
		$crc = sprintf("%u", crc32($pid));
		$path = substr($crc, 0, 2) . "/" . substr($crc, 2, 2) . "/"  . $pid . '.'. $ext;
		return $path;
	}
	
	//获取pid
	public function create_pid($module, $ext, $uuid = null)
	{
		$ci = & get_instance();
		$ext = strtolower($ext);
		if($uuid == null) {
			$ci->load->model('Attachment_Model');
			$uuid = $ci->Attachment_Model->insert(array('ext' => $ext, 'module' => $module));
		}
		$ci->load->library('CT_Mcrypt');
		$ext_arr = array_flip($this->ext);
		$exten = $ext_arr[$ext];
		$module_arr = array_flip($this->module);
		$module_name = $module_arr[$module];
		$filename = $module_name . "_" . $uuid . "_" . $exten;
		$pid = $ci->ct_mcrypt->encode($filename);
		return $pid;
	}
	
	//pid转url
	public function pid2url($pid, $w = 0 , $h = 0)
	{
	   if(empty($pid) || strlen($pid) < 18) {
			return "";
		} 
		$ci = & get_instance();
		$ci->load->library('CT_Mcrypt');
		$source = $ci->ct_mcrypt->decode($pid);
		$fileinfo  = explode("_", $source);
		$exten = $fileinfo[2];
		$ext = $this->ext[$exten];
		$crc = sprintf("%u", crc32($pid));
		$path = substr($crc, 0, 2) . "/" . substr($crc, 2, 2) . "/"  . $pid . '.'. $ext;
		$module_arr = $this->module;
		$module_name = $module_arr[$fileinfo[0]];
		$size = $this->makesize($w, $h);
		$count = count($this->img_host);
		$host = $this->img_host[$crc % $count];
		$img_url = $host. "/". $module_name. "/" . $size . "/" . $path;
		return $img_url;
		
	}
	
	//pid读取文件内容
	public function pid2content($pid, $w = 0 , $h = 0)
	{
		if(empty($pid) || strlen($pid) < 20) {
			return "";
		}
		$ci = & get_instance();
		$ci->load->library('CT_Mcrypt');
		$source = $ci->ct_mcrypt->decode($pid);
		$ci = & get_instance();
		$ci->config->load('image', TRUE);
		$config_image = $ci->config->item('image');
		$fileinfo  = explode("_", $source);
		$exten = $fileinfo[2];
		$ext = $this->ext[$exten];
		$crc = sprintf("%u", crc32($pid));
		$path = substr($crc, 0, 2) . "/" . substr($crc, 2, 2) . "/"  . $pid . '.'. $ext;
		$module_arr = $this->module;
		$module_name = $module_arr[$fileinfo[0]];
		$size = $this->makesize($w, $h);
		//适配生产环境，跨服务器请求
		if(ENVIRONMENT == 'production') {
		    $real_path = "http://172.29.164.103" .  "/". $module_name. "/" . $size . "/" . $path;
		} else {
    		$real_path = $this->root_path .  "/". $module_name. "/" . $size . "/" . $path;
		}
		$ci->load->library('encrypt');
		$data = file_get_contents($real_path);
		$data = $ci->encrypt->decode($data);
		return $data;
	
	}
	
	/**
	 * debug pid信息
	 * @param unknown $pid
	 * @return multitype:
	 */
	public function pidinfo($pid)
	{
		$ci = & get_instance();
		$ci->load->library('CT_Mcrypt');
		$source = $ci->ct_mcrypt->decode($pid);
		return explode("_", $source);
	}
	
	/**
	 * 图片上传模块
	 * @param unknown $module
	 * @return boolean|multitype:multitype:string unknown  multitype:unknown Ambigous <number, unknown>
	 */
	public function doupload($module)
	{
		$ci = & get_instance();
		$ci->load->config('image', true);
		$config = $ci->config->item('image');
		
		$size_arr = isset($config[$module]['resize']) ? explode("|", $config[$module]['resize']) : array();
		$is_encrypt = isset($config[$module]['encrypt']) ? $config[$module]['encrypt'] : false;
		$save_path = $config['path'];
		$images = array();
		foreach ($_FILES as $field => $fileinfo) {
			if (isset($_FILES[$field])  && is_uploaded_file($_FILES[$field]["tmp_name"]) && $_FILES[$field]["error"] === 0) {
				$upload_file = $_FILES[$field];
				$file_info   = pathinfo($upload_file['name']);
				$file_type   = $file_info['extension'];
				$file_type = strtolower($file_type);
				if(false == in_array($file_type, array_values($this->ext))) {
				    continue;
				}
				$pid = $this->create_pid($module, $file_type);
				$ab_path = $this->pid2path($pid);
				$save   = $save_path .  $module . "/" . 'origin'  . "/" . $ab_path;
				if(file_exists(dirname($save)) == false) {
					mkdir(dirname($save), DIR_WRITE_MODE, true);
				}
				$name        = $_FILES[$field]['tmp_name'];
				if (!move_uploaded_file($name, $save)) {
					return false; 
				}
				//加密处理
				if($is_encrypt) {
				    $data = file_get_contents($save);
				    $ci->load->library('encrypt');
					$data = $ci->encrypt->encode($data);
					file_put_contents($save, $data);
				}
				$url = $this->pid2url($pid);
				$images[] = array('pid' => $pid, 'url' => $url, 'w' => 'origin', 'h' => 'origin');
				if($size_arr) {
					foreach ($size_arr as $size) {
						$sizeinfo = explode("*", $size);
						$w = $sizeinfo[0];
						$h = isset($sizeinfo[1]) ? $sizeinfo[1] : 0;
						$this->resize($pid, $w, $h);
						$url = $this->pid2url($pid, $w, $h);
						$images[] = array('pid' => $pid, 'url' => $url, 'w' => $w, 'h' => $h);
					}
				}
			}
		}
		return $images;
	}
	
}